using System;
using System.Collections.Generic;
using System.Linq;
using Cmc.Modbus.Base;
using NewLife;
using NewLife.Net;

namespace Cmc.Modbus
{
    public class DefaultClientFactory : IClientFactory
    {
        static Dictionary<string, IClient> clients = new Dictionary<string, IClient>();
        public IClient GetClient(CommunicationType communicationType, string ip, int port, object param = null)
        {
            string key = $"{ip}:{port}:{communicationType}";
            if (clients.ContainsKey(key))
            {
                return clients[key];
            }

            IClient client;
            switch (communicationType)
            {
                case CommunicationType.TcpClient:
                    client = new TcpClient(ip, port, Received);
                    break;
                case CommunicationType.UdpServer:
                    if (param==null)
                    {
                        throw  new Exception("Modbus协议 UdpServer没有初始化！");
                    }
                    client = new UdpServerClient(ip, port, param as NetServer, Received);
                    break;
                case CommunicationType.TcpServer:
                    if (param == null)
                    {
                        throw new Exception("Modbus协议 TcpServer没有初始化！");
                    }
                     client = new TcpServerClient(ip, port, param as NetServer, Received);
                    break;
                default:
                    client = new UdpClient(ip, port, Received);
                    break;
            }

            clients.Add(key, client);
            return client;
        }

        void Received(object s, ReceivedEventArgs e)
        {
             //接收数据的其他处理
        }
    }
}
